$(function () {
	var national = [
        "--请选择--","汉族", "壮族", "满族", "回族", "苗族", "维吾尔族", "土家族", "彝族", "蒙古族", "藏族", "布依族", "侗族", "瑶族", "朝鲜族", "白族", "哈尼族",
        "哈萨克族", "黎族", "傣族", "畲族", "傈僳族", "仡佬族", "东乡族", "高山族", "拉祜族", "水族", "佤族", "纳西族", "羌族", "土族", "仫佬族", "锡伯族",
        "柯尔克孜族", "达斡尔族", "景颇族", "毛南族", "撒拉族", "布朗族", "塔吉克族", "阿昌族", "普米族", "鄂温克族", "怒族", "京族", "基诺族", "德昂族", "保安族",
        "俄罗斯族", "裕固族", "乌孜别克族", "门巴族", "鄂伦春族", "独龙族", "塔塔尔族", "赫哲族", "珞巴族"
    ];
	initNations();
	function initNations(){
		var nat  = document.getElementById("nations");
		for ( var i = 0; i < national.length; i++) {
			var option = document.createElement ('option');
			option.value = i;
			var txt = document.createTextNode (national[i]);
			option.appendChild (txt);
			nat.appendChild (option);
		}
//		$("#nations").html('<option value="">--请选择--</option>'+opt);
		$('#nations').trigger('chosen:updated');
    	$("#nations").chosen({no_results_text: "没有匹配项"});
        $('.chosen-container').width('100%');
	}
    $(".phoneBelong").on({
        focus: function () {
            $('.attribution').show();
        },
        click: function () {
            $('.attribution').show();
        },
    });
	$('.addInquiries').on('hidden.bs.modal', function () {

		$("#city").val("");
		$("#city").trigger("chosen:updated");
		$("#province").val("");
		$("#province").trigger("chosen:updated");
		$("#departmentId1").val("");
		$("#departmentId1").trigger("chosen:updated");
		$("#projectId").val("");
		$("#projectId").trigger("chosen:updated");
		$('#inquiries')[0].reset();
		$('#inquiries input:hidden').val('');
		$('#inquiries textarea:hidden').val('');
		editor.html('');
		$('#inquiries .selectpicker').selectpicker('refresh');
		$('#inquiries').data('bootstrapValidator').resetForm();
	})
	
	//时间初始化
    $.fn.datetimepicker.dates['zh'] = {  
            days:       ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期日"],  
            daysShort:  ["日", "一", "二", "三", "四", "五", "六","日"],  
            daysMin:    ["日", "一", "二", "三", "四", "五", "六","日"],  
            months:     ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月","十二月"],  
            monthsShort:  ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],  
            meridiem:    ["上午", "下午"],  
            today:       "今天"  
    };  
    //期待回访日期
    $(".recordnexttime").datetimepicker({
    	language:  'zh',  
    	format: 'yyyy-mm-dd hh:ii',
    	autoclose: true
    });
    
	//电话归属地获取值
    function chose_get_value(select){
        return $(select).val();
    }

    //电话归属地获取选中的文本
    function chose_get_text(select){
        return $(select+" option:selected").text();
    }
	
    function phoneBelong(parentEle) {
		 $(parentEle).find('.attribution .confirm-btn').click(function () {
             if(chose_get_value(parentEle+' #province') != 0 && chose_get_value(parentEle+' #city') != 0){
                 $(parentEle).find('.phoneBelong').val(chose_get_text(parentEle+' #province') + chose_get_text(parentEle+' #city'));
                 $(parentEle).find('.attribution').fadeOut();
             }
		 });
        $(parentEle).find('.attribution .cancel-btn').click(function () {
              $(parentEle).find('.attribution').fadeOut();
        });
        
    }
    
    //咨询者类型为在线有效时，对话记录为必填项
    $("#studentAttrId2").change(function(){
      if($("#studentAttrId2").find("option:selected").text()=="在线有效"){
        $("#talk").addClass("control-label mandatory").html("*");
        $("#talk").parent().removeClass("padding-right-5");
      }else{
        $("#talk").removeClass("control-label mandatory").html("");
        $("#talk").parent().addClass("padding-right-5");
      }
    })
    
    //创建咨询量
    phoneBelong('#addInquiries');

    //重复电话添加新咨询课程
    phoneBelong('#addRepeatedPhone');

    //日期控件
    $('#reservation').daterangepicker({
    	locale : {  
	    	format: 'YYYY-MM-DD',
	    	separator:' - ',
	        applyLabel : '确定',  
	        cancelLabel : '取消',  
	        customRangeLabel : '自定义',  
	        daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],  
	        monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',  
	                '七月', '八月', '九月', '十月', '十一月', '十二月' ],  
	        firstDay : 1 , 
	    },  
	    ranges: {
			'今天': [moment().startOf('day'), moment()],
			'昨天': [moment().subtract(1,'days').startOf('day'), moment().subtract(1,'days').endOf('day')],
			'本周': [moment().startOf("week").add(1,'days'),moment().endOf("week").add(1,'days')],
			'上周': [moment().subtract(1,'weeks').startOf("week").add(1,'days'),moment().subtract(1,'weeks').endOf("week").endOf("week").add(1,'days')],
			'本月': [moment().startOf("month"),moment().endOf("month")],
			'上个月': [moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],
			'最近7天': [moment().subtract(6,'days'), moment()],
			'最近30天': [moment().subtract(29,'days'), moment()]
	     },
	     applyClass:'btn-primary',
	     alwaysShowCalendars: true,
	     autoclose:true
    });
    //初始化分校select 
	$.ajax({
        url: ctx + '/department/getAllOption',
        type: 'POST',
        data: {type : 3},
        dataType: 'json',
        success: function (data) {
    		var opt = "";
        	for(var i=0; i<data.list.length; i++){
        		opt += "<option value="+data.list[i].departmentId+">" + data.list[i].fullName+ "</option>";
        	}
        	$("#departmentId1").html('<option value="">--请选择--</option>'+opt);
            $('#departmentId1').trigger('chosen:updated');
            $("#departmentId1").chosen({no_results_text: "没有匹配项"});
            $('.chosen-container').width('100%');
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始化招生品牌
	$.ajax({
        url: ctx + '/bizBrand/getAllOption',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
    		var opt = "";
        	for(var i=0; i<data.list.length; i++){
        		opt += "<option value="+data.list[i].brandId+">" + data.list[i].brandName+ "</option>";
        	}
        	$("#brandId").html('<option value="">--请选择--</option>'+opt);
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始化咨询者类型
	$.ajax({
        url: ctx + '/studentAttr/getAllOption',
        type: 'POST',
        data: {attrType : 2},
        dataType: 'json',
        success: function (data) {
    		var zxz = "";
        	for(var i=0; i<data.list.length; i++){
        		zxz += "<option value="+data.list[i].studentAttrId+">" + data.list[i].typeName + "</option>";
        	}
        	$("#studentAttrId2").html('<option value="">--请选择--</option>'+zxz);
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始化媒体来源类型
	$.ajax({
        url: ctx + '/studentAttr/getAllOption',
        type: 'POST',
        data: {attrType : 1},
        dataType: 'json',
        success: function (data) {
    		var mt = "";
        	for(var i=0; i<data.list.length; i++){
        		mt += "<option value="+data.list[i].studentAttrId+">" + data.list[i].typeName + "</option>";
        	}
        	$("#studentAttrId1").html('<option value="">--请选择--</option>'+mt);
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始化学历
	$.ajax({
        url: ctx + '/studentAttr/getAllOption',
        type: 'POST',
        data: {attrType : 3},
        dataType: 'json',
        success: function (data) {
    		var xl = "";
        	for(var i=0; i<data.list.length; i++){
        		xl += "<option value="+data.list[i].studentAttrId+">" + data.list[i].typeName + "</option>";
        	}
        	$("#highestEducationName").html('<option value="">--请选择--</option>'+xl);
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始咨询课程
	$.ajax({
        url: ctx + '/bizProject/getAll',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
    		var zxkc = "";
        	for(var i=0; i<data.list.length; i++){
        		zxkc += "<option value="+data.list[i].projectId+">" + data.list[i].fullName + "</option>";
        	}
        	$("#projectId").html('<option value="">--请选择--</option>'+zxkc);
        	$('#projectId').trigger('chosen:updated');
            $("#projectId").chosen({no_results_text: "没有匹配项",search_contains: true});
            $('.chosen-container').width('100%');
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//咨询课程级别
	$('#projectId').change(function(){
		var projectId= $('#projectId :selected').val();
		$.ajax({
	        url: ctx + '/bizProjectLevel/getAllOption',
	        type: 'POST',
	        data: {projectId : projectId},
	        dataType: 'json',
	        success: function (data) {
	    		var level = "";
	        	for(var i=0; i<data.list.length; i++){
	        		level += "<option value="+data.list[i].projectLevelId+">" + data.list[i].levelTitle + "</option>";
	        	}
	        	$("#projectLevelId").html('<option value="">--请选择--</option>'+level);
	        },
	        error: function (response) {
	        	toastr.error("系统错误");
	        }
	    });
	});
	//初始化电话归属地（省）
	$.ajax({
        url: ctx + '/address/getAllOption',
        type: 'POST',
        data: {level : 1},
        dataType: 'json',
        success: function (data) {
    		var sheng = "";
        	for(var i=0; i<data.list.length; i++){
        		sheng += "<option value="+data.list[i].addressId+">" + data.list[i].fullName + "</option>";
        	}
        	$("#province").html('<option value="0">--请选择--</option>'+sheng);
        	$('#province').trigger('chosen:updated');
        	$("#province").chosen({no_results_text: "没有匹配项"});
	        $('.chosen-container').width('100%');
        },
        error: function (response) {
        	toastr.error("系统错误");
        }
    });
	//初始化电话归属地（市）
	$('#province').change(function(){
		var addressId= $('#province :selected').val();
		$.ajax({
	        url: ctx + '/address/getAllOption',
	        type: 'POST',
	        data: {level : 2,addressId:addressId},
	        dataType: 'json',
	        success: function (data) {
	    		var shi = "";
	        	for(var i=0; i<data.list.length; i++){
	        		shi += "<option value="+data.list[i].addressId+">" + data.list[i].fullName + "</option>";
	        	}
	        	$("#city").html('<option value="0">--请选择--</option>'+shi);
	            $('#city').trigger('chosen:updated');
	            $("#city").chosen({no_results_text: "没有匹配项"});
	            $('.chosen-container').width('100%');
	        },
	        error: function (response) {
	        	toastr.error("系统错误");
	        }
	    });
	});
    /**
     * 创建咨询量
     *
     */
    
})


DataTable.init();
/**
 * 回调函数
 * @param sSource
 * @param aoData
 * @param fnCallback
 * @returns
 */
function retrieveData( sSource, aoData, fnCallback, oSettings ) {
	var beganAndEnd = $("#reservation").val();
	if(beganAndEnd && beganAndEnd.length != 0){
    	var minDate = trim(beganAndEnd.split(" - ")[0]);
        var maxDate = trim(beganAndEnd.split(" - ")[1]);
        aoData.push({ "name": "beginTime", "value": minDate });
        aoData.push({ "name": "endTime", "value": maxDate });
    }
    aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
    aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength });  
    aoData.push( { "name": "catRolEnable", "value": 0 }); 
    var searchVal = $('#searchVal').val();
    
    if(searchVal && searchVal.length != 0){
    	aoData.push({ "name": "searchVal", "value": searchVal });
    }
    
    $.ajax( {  
        "url": sSource,  
        "data": aoData,  
        "cache": false,  
        "dataType": 'json', 
        "type": "POST", 
        "success" :function(response) {
        	fnCallback(response.returnObject);
        }  
    } );  
    $('.dataTables_info').parent().append($('.dataTables_length'));
}

function deleteInfoManage(id){
	var infoManageId = id;
	$.ajax({
        url: ctx + '/consultInfoManage/updateRecord',
        type: 'POST',
        data: {
        	infoManageId:infoManageId,
        	deleteMark:0
        },
        dataType: 'json',
        success: function (data) {
        	if(data.status == 'success'){
        		DataTable.init();
        	}else{
        		toastr.error(data.msg);
        	}
        }
	});
}


$('#infoManage').on('click', '.edit', function(){
	
	var record = $(this).data('record');
	
	$('#departmentName1').val(record.departmentName1);
	$('#phoneBelongView').val(record.phoneBelong);
	$('#brandNameView').val(record.brandName);
	$('#studentAttrName2').val(record.studentAttrName2);
	$('#studentAttrName1').val(record.studentAttrName1);
	$('#keywordView').val(record.keyword);
	$('#pageUrlView').val(record.pageUrl);
	$('#studentNameView').val(record.studentName);
	$('#studentPhoneView').val(record.studentPhone);
	$('#studentSexView').val(record.studentSex?"女":"男");
	$('#wechatView').val(record.weChat);
	$('#ageView').val(record.age);
	$('#tengXunView').val(record.tengXun);
	$('#projectNameView').val(record.projectName);
	$('#projectLevelNameView').val(record.projectLevelName);
	$('#highestEducationView').val(record.highestEducation);
	$('#notesView').val(record.notes);
	$('#conversationView').val(record.conversation);
	$('#majorNameView').val(record.majorName);
	$('#nationView').val(record.nation);
	$('#emergencyContactView').val(record.emergencyContact);
	$('#emergencyContactModeView').val(record.emergencyContactMode);
	$('#graduateInstitutionsView').val(record.graduateInstitutions);
	
	editor2.html(record.conversation);
	
	$('#viewInfo').modal('show');
	
})

//表单验证
$('#inquiries').bootstrapValidator({
	message: 'This value is not valid',
    fields: {
    	studentPhone: {
            validators: {
                notEmpty: {
                    message: '电话不能为空'
                },
                regexp: {
                    regexp: /^[1-9]\d{10}$/,
                    message: '格式错误'
                }
            }
        },
        brandId:{
        	validators: {
        		 notEmpty: {
                     message: '招生品牌不能为空'
                 },
        	}
        },
        studentAttrId2:{
        	validators: {
        		 notEmpty: {
                     message: '咨询者类型不能为空'
                 },
        	}
        },
        studentAttrId1:{
        	validators: {
        		 notEmpty: {
                     message: '媒体来源不能为空'
                 },
        	}
        },
        keyword:{
        	validators: {
        		 notEmpty: {
                     message: '关键词不能为空'
                 },
        	}
        },
        tengXun:{
        	validators: {
                 regexp: {
                     regexp: /^[0-9]*$/,
                     message: 'qq号只有数字组成'
                 }
        	}
        },
        studentName:{
        	validators: {
        		 notEmpty: {
                     message: '姓名不能为空'
                 }
        	}
        },
        age:{
        	validators: {
        		regexp: {
                    regexp: /^(?:[1-9][0-9]?|1[01][0-9]|120)$/,
                    message: '年龄必输为数字'
                },
        	}
        }
    },
    submitHandler: function (validator, form, submitButton) { 
    	var brandId = $('#brandId :selected').val();
    	var projectId = $('#projectId :selected').val();
    	if(projectId==null||projectId==""){
    		toastr.error("请选择咨询课程!");
   		  	return;
    	}
    	var studentPhone = $('#inquiries :input[name="studentPhone"]').val();
    	var departmentId1 = $('#departmentId1 :selected').val();
    	if(departmentId1==null||departmentId1==""){
    		toastr.error("请选择信息归属地!");
   		  	return;
    	}
    	$.ajax({
			url : ctx + '/consultInfoManage/getAllOption',
			type: 'POST',
			data:{brandId:brandId,projectId:projectId,studentPhone:studentPhone},
			dataType: 'json',
			async:true,
			success: function (data) {
				if(data.list.length==0){
					var phoneBelong = $('#inquiries :input[name="phoneBelong"]').val();
			    	if(phoneBelong==null||phoneBelong==""){
			    		toastr.error("请选择电话归属地!");
			   		  	return;
			    	}
		        var projectId = $('#projectId :selected').val();
		        var departmentId1 = $('#departmentId1 :selected').val();
		        var brandId = $('#brandId :selected').val();
		        var brandSchool = '^\\[[[:print:]]*\\{\\"brand\\"\\:\\"'+brandId+'\\"\\,\\"school\\"\\:\\[[a-zA-Z0-9\\-\\,\\"]*\\"'+departmentId1+'\\"[a-zA-Z0-9\\-\\,\\"]*\\]\\}[[:print:]]*\\]$';
	        	  var options = form.serialize();
	              var departmentName1 = $('#departmentId1 :selected').text();
	              var brandName = $('#brandId :selected').text();
	              var studentAttrName1 = $('#studentAttrId1 :selected').text();
	              var studentAttrName2 = $('#studentAttrId2 :selected').text();
	              if(studentAttrName2=='在线有效'){
	            	  var dialogueLink = $('#inquiries textarea[name="conversation"]').val();
	            	  if(dialogueLink==null||dialogueLink==""){
	            		  toastr.error("请填写对话记录!");
	            		  return;
	            	  }
	              }
	             var projectName = $('#projectId :selected').text();
	             var projectLevelName = $('#projectLevelId :selected').text();
	             var highestEducation = $('#highestEducationName :selected').text();
	             var nation = $('#nations :selected').text();
	             var nation = $('#nations :selected').text();
	             var recordnexttimees = $('#inquiries input[name="recordnexttime"]').val();
	             var recordnexttime='';
	             if(recordnexttimees==""||recordnexttimees==null){
	            	 var d=new Date();var year=d.getFullYear().toString();var month=(d.getMonth()+1).toString();var day=d.getDate().toString();var hour=(d.getHours()+1).toString();
	            	 var minute = d.getMinutes().toString(); 
	            	 if(month.length ==1){
	            		 month = "0" + 1;
	            	 }
	            	 if(day.length ==1){
	            		 day = "0" + 1;
	            	 }
	            	 if(hour.length ==1){
	            		 hour = "0" + 1;
	            	 }
	            	 if(minute.length ==1){
	            		 minute = "0" + 1;
	            	 }
	            	 var recordnexttime1 = ''+year+'-'+month+'-'+day+' '+hour+':'+minute+'';
	            	 recordnexttime = recordnexttime1;
	             }else{
	            	 recordnexttime = recordnexttimees;
	             }
	             options += "&recordNextTime=" + recordnexttime;
	        	 options += "&departmentName1=" + departmentName1;
	             options += "&brandName=" + brandName;
	             options += "&studentAttrName1=" + studentAttrName1;
	             options += "&studentAttrName2=" + studentAttrName2;
	             options += "&projectName=" + projectName;
	             options += "&projectLevelName=" + projectLevelName;
//	             options += "&departmentName2=" + departmentName2;
	             options += "&highestEducation=" + highestEducation;
	             options += "&nation=" + nation;
	         	$.ajax({
	                type: "POST",
	                url:  ctx + '/consultInfoManage/addNewRecord',
	                data: options,
	                dataType: 'json',
	                success: function (data) {
	                	 if (data.status == "success"){
	                		 DataTable.init();
	                		 $('.addInquiries').modal('hide');
	                	 }else{
	                		 toastr.error(data.msg);
	                	 }
	                },
	                error: function (msg) {
	                	toastr.error("系统错误");
	                }
	            });
				}else{
					toastr.error("在"+data.list[0].createDate+","+data.list[0].createUserName+"已创建该咨询课程和招生品牌的咨询量，请核对后输入！");
					return;
				}
			},
			error: function (response) {
	        	toastr.error("系统错误");
	        }
		});
    }
});
//每页显示记录数

//回车搜索
function search(){
	if(event.keyCode==13){
		DataTable.init();
	}
}

